// pages/talents/talentsDetail/talentDetail.js
const app = getApp()
import { request } from '../../../utils/api'
import Dialog from '../../../vant/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 自定义nav
    statusBarHeight1: app.globalData.statusBarHeight+45,
    active: 0,
    // 打赏盒子
    showDS: false,
    // 金额
    money: '',
    // 是否打赏成功
    dsSuc: false,
    // 支付金额
    payNum: 5,
    // 人才id
    userId: '',
    // 用户详情
    userData: {},
    // 作品集合
    zuoPinList: [],
    // 证书集合
    zhengShuList: [],
    // 问答列表
    qaList: [],
    // 图片基础路径
    imgBaseUrl: app.globalData.imgBaseUrl,
    openId: '',
    // 当前登录用户id
    loginId: '',
    // 显示回答弹窗
    showAnswer: false,
    // 回答内容
    answerValue: '',
    // 回答图片
    answerImgList: [],
    imgStr: '',
    // 点击回答的问题id
    qId: '',
    height: { maxHeight: 200, minHeight: 150 },
    // 擅长类型
    shanChang: ''
  },
  // 返回
  goBack() {
    wx.navigateBack({
      delta: 1
    })
  },
  // 图片预览
  onPreview(e) {
    app.onPreviewImg(e.currentTarget.dataset.url)
  },
  // 加关注
  guanzhu() {
    wx.getStorage({
      key: 'userInfo',
      success: (res) => {
        console.log(res);
        request({
          url: '/zhongyisheji-applet/lookUser/private/guanzhu',
          method: 'post',
          data: {
            userId: this.data.userId
          }
        }).then(res => {
          console.log(res);
          if(res.code == 200) {
            wx.showToast({
              title: '关注成功',
            })
            this.getUserDetail()
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        })
      },
      fail: (res1) => {
      Dialog.confirm({
          title: '提示',
          confirmButtonText: '立即登录',
          message: '您暂未登录，请先登录才能关注',
        })
        .then(() => {
          wx.redirectTo({
            url: '/pages/login/login',
          })
        })
        .catch(() => {
          // on cancel
          Dialog.close()
        });
      }
    })
   
  },
  // 切换兰事件
  onChange(event) {
    let title = event.detail.title
    if(title == '代表作品') {
      this.getZuoPin()
    } else if (title == '荣誉证书') {
      this.getZhengShu()
    } else if (title == '有问必答') {
      this.getQA()
    }
  },
  // 向TA提问
  onQues() {
    console.log('提问');
    wx.getStorage({
      key: 'userInfo',
      success: (res) => {
        console.log(res);
        wx.navigateTo({
          url: '/pages/talents/question/question?userId='+this.data.userId,
        })
      },
      fail: (res1) => {
      Dialog.confirm({
          title: '提示',
          confirmButtonText: '立即登录',
          message: '您暂未登录，请先登录才能提问',
        })
        .then(() => {
          wx.redirectTo({
            url: '/pages/login/login',
          })
        })
        .catch(() => {
          // on cancel
          Dialog.close()
        });
      }
    })
   
    
  },
  // 切合合作
  onJoin() {
    console.log('合作');
    wx.navigateTo({
      url: '/pages/talents/callUs/callUs?phone='+this.data.userData.userDetils.phone,
    })
  },
  // 打赏
  daShang() {
    console.log('打赏');
    this.setData({ showDS: true });
  },
  // 关闭打赏弹出侧
  onClose() {
    this.setData({ showDS: false });
  },
  // 确认支付
  goBuy() {
    console.log(this.data.payNum);
    // this.setData({
    //   showDS: false,
    //   dsSuc: true
    // })
    this.setData({
      showDS: false,
    })
    // 下面该吊起支付了！！
    // 获取订单号
    request({
      url: '/zhongyisheji-applet/lookUser/private/dashang',
      method: 'post',
      data: {
        money: this.data.payNum,
        rencaiId: this.data.userId
      }
    }).then( res => {
      console.log(res);
      if(res.code == 200 && res.data.orderNumber) {
        // orderNum = res.data.orderNumber
        request({
          url: '/zhongyisheji-applet/pay/launchWxPay',
          method: 'post',
          data: {
            orderNumber: res.data.orderNumber,
            openid: this.data.openId
          }
        }).then(res1 => {
          console.log(res1);
           if(res1.code == 200) {
            //  拉起微信祝支付
            wx.requestPayment({
              appId: res1.appId,
              timeStamp: res1.data.timeStamp,
              nonceStr: res1.data.nonce_str,
              package: res1.data.package,
              signType: res1.data.signType,
              paySign: res1.data.paySign,
              success (res) { 
                console.log('支付成功');
                // 付款成功跳转到  我的订单
                // wx.navigateTo({
                //   url: '/pages/mine/myOrder/myOrder',
                // })
                wx.showToast({
                  title: '支付成功'
                })
              },
              fail (res) { 
                console.log(res);
                wx.showToast({
                  title: '付款失败！',
                  icon: 'none'
                })
                
              }

            })
           }
        })
      } else {
        wx.showToast({
          title: ress.msg,
          icon: 'none'
        })
      }
    })
  },
  // 跳转作品详情
  goWorksDetail(e) {
    console.log(e);
    
    wx.navigateTo({
      url: '/pages/worksDetail/worksDetail?zpId=' + e.currentTarget.dataset.id + '&userId=' + this.data.userId, 
    })
  },
  // 问题图片预览
  imgYu(e) {
    wx.previewImage({
      urls: [this.data.imgBaseUrl + e.currentTarget.dataset.src],
      current: this.data.imgBaseUrl + e.currentTarget.dataset.src, // 当前显示图片的http链接
    })
  },
  // 回答问题
  onAnswer(e) {
    if(this.data.loginId != this.data.userId) {
      wx.showToast({
        title: '您是不是该作品的作者，不能进行回答',
        icon: 'none',
        duration: 2000
      })
      return
    }
    this.setData({
      showAnswer: true,
      qId: e.currentTarget.dataset.qid
    })
  },
  // 回答问题上传图片
  // 文件上传事件
  afterRead(event) {
    const { file } = event.detail;
    let that = this
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: app.globalData.imgUploadUrl, // 仅为示例，非真实的接口地址
      filePath: file.path,
      name: 'photo',
      success(res) {
        console.log(res);
        res.data = JSON.parse(res.data)
        // 上传完成需要更新 fileList
        const { fileList = [] } = that.data;
        fileList.push({ ...file, url: that.data.imgBaseUrl + res.data.data });
        that.setData({ 
          fileList,
          imgStr: that.data.imgStr + res.data.data + ','
         });
      },
    });
  },
  // 关闭回答问题弹窗
  onClose1() {
    this.setData({ close: false });
  },
  // 确认提交回答
  submitAnswer() {
    console.log(1);
    if(!this.data.answerValue.trim()) {
      wx.showToast({
        title: '请输入回答内容',
        icon: 'none'
      })
      return
    }
    this.setData({
      showAnswer: false
    })
    request({
      url: '/zhongyisheji-applet/lookUser/private/answerUser',
      method: 'post',
      data: {
        id: this.data.qId,
        content: this.data.answerValue,
        answerImage: this.data.imgStr
      }
    }).then(res => {
      if(res.code == 200) {
        wx.showToast({
          title: '回答成功',
        })
        this.getQA()
      } else {
        wx.showToast({
          title: '回答失败',
          icon: 'none'
        })
      }
    })
  },
  // 选择打赏金额时
  payNum(e) {
    // console.log(e.currentTarget.dataset.num);
    this.setData({
      payNum: e.currentTarget.dataset.num
    })
  },
  // 获取用户详情
  getUserDetail() {
    request({
      url: '/zhongyisheji-applet/lookUser/public/userDetils',
      method: 'post',
      data: {
        userId: this.data.userId
      }
    }).then(res => {
      console.log(res);
      if(res.code == 200) {
        res.data.userDetils.address = res.data.userDetils.address.split('-')
        this.setData({
          userData: res.data,
          shanChang: res.data.listAdeptType.length != 0 ? res.data.listAdeptType.join(',') : ''
        })
      }
    })
  },
  // 获取用户作品
  getZuoPin() {
    request({
      url: '/zhongyisheji-applet/lookUser/public/selectMyProduction',
      method: 'post',
      data: {
        userId: this.data.userId
      }
    }).then(res => {
      console.log('作品',res);
      if(res.code == 200) {
        this.setData({
          zuoPinList: res.data
        })
      }
    })
  },
  // 获取荣誉证书
  getZhengShu() {
    request({
      url: '/zhongyisheji-applet/lookUser/public/selectMyCertificateList',
      method: 'post',
      data: {
        userId: this.data.userId
      }
    }).then(res => {
      if(res.code == 200) {
        console.log('证书',res);
        this.setData({
          zhengShuList: res.data
        })
      }
    })
  },
  // 获取有问必答数据
  getQA() {
    request({
      url: '/zhongyisheji-applet/lookUser/public/wendaList',
      method: 'post',
      data: {
        pageNum: '1',
        pageSize: '99',
        rencaiId: this.data.userId
      }
    }).then(res => {
      console.log('问答',res);
      if(res.code == 200) {
        if(res.data.records.length != 0) {
          res.data.records.filter(item => {
            item.askImage = item.askImage.slice(0,-1).split(',')
            item.answerImage = item.answerImage.slice(0,-1).split(',')
          })
         
        }
        this.setData({
          qaList: res.data.records
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options);
    // 这个是人才id
    let userId = options.userId 
    this.setData({
      userId: userId
    })
    // 判断是否从消息通知那来的
    let type = options.type
    if (type == 2) {
      this.setData({
        active: 2
      })
    }
    wx.getStorage({
      key: 'codeData',
      success: res => {
        this.setData({
          openId: res.data.openid
        })
      }
    })
    wx.getStorage({
      key: 'userInfo',
      success: res => {
        this.setData({
          loginId: res.data.userId
        })
      }
    })
    this.getUserDetail()
    this.getZuoPin()
    this.getZhengShu()
    this.getQA()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
  //  */
  // onShareAppMessage: function () {

  // }
})